/*
 * @Description: 流转按钮
 * @Author: Zzt
 * @Date: 2022-09-28 14:57:08
 * @LastEditTime: 2023-01-06 17:15:49
 */

import { useEffect, useState } from 'react';
import { Button, Popover } from 'antd';
import { circulationArchivesMethod } from '@/api/archives/scattered';
import { fetchRepoListByType } from '@/api/archivesType';
import type { IRepo } from '@/interfaces/archiveType';
interface ICirculationProps {
  selectItems: number[];
  baseInfo: any;
}
const Circulation = (props: ICirculationProps) => {
  const { selectItems, baseInfo } = props;
  console.log('baseInfo', baseInfo, selectItems);

  // popover显示状态
  const [visible, setVisible] = useState(false);
  // 目标库列表
  const [roamToList, setRoamToList] = useState<IRepo[]>([]);

  /**
   * @description: 监听档案类型变化请求库列表
   */
  useEffect(() => {
    baseInfo &&
      selectItems.length > 0 &&
      fetchRepoListByType(baseInfo.atType, baseInfo.id).then((res: any) => {
        const { data } = res;
        setRoamToList(data.filter((repo: IRepo) => repo.createStatus));
      });
  }, [baseInfo]);

  /**
   * @description: 流转接口
   * @param {IRepo} props
   * @return {*}
   */
  const toDb = (props: IRepo): void => {
    const { atCode, atType, atLevel, dbName } = baseInfo;
    circulationArchivesMethod({
      coordinate: { atCode, atType, level: atLevel },
      fromDb: dbName,
      movingEntryInfo: { entryIdList: selectItems, searchCondition: '' },
      toDb: props.name
    });
  };

  /**
   * @description: 监听popover弹层显示状态方法
   * state为false时关闭。打开使用按钮控制
   * @param {boolean} visibleState
   * @return {*}
   */
  const handleOpenChange = (visibleState: boolean): void => {
    !visibleState && setVisible(visibleState);
  };

  /**
   * @description: 弹层内容
   */
  const roamTo = (
    <>
      {roamToList
        .filter((repo) => repo.name !== baseInfo.dbName)
        .map((item) => (
          <div key={item.id}>
            <Button type="text" onClick={() => toDb(item)}>
              {item.description}
            </Button>
          </div>
        ))}
    </>
  );

  return (
    <Popover
      visible={visible}
      content={roamTo}
      trigger={['click']}
      placement="bottom"
      onVisibleChange={handleOpenChange}
    >
      <Button
        disabled={selectItems.length === 0}
        onClick={() => {
          setVisible(true);
        }}
      >
        流转
      </Button>
    </Popover>
  );
};
export default Circulation;
